 /*
  * Copyright (c) 2021, 2023, yishun.cn All rights reserved.
  *
  */
 package cn.shun.advice;

 import cn.hutool.core.lang.Dict;
 import cn.hutool.json.JSONUtil;
 import cn.shun.dto.PageInfoDto;
 import cn.shun.dto.ResponseDto;
 import cn.shun.exception.BizException;
 import cn.shun.local.PageInfoThreadLocal;
 import org.springframework.core.MethodParameter;
 import org.springframework.http.MediaType;
 import org.springframework.http.converter.HttpMessageConverter;
 import org.springframework.http.converter.StringHttpMessageConverter;
 import org.springframework.http.server.ServerHttpRequest;
 import org.springframework.http.server.ServerHttpResponse;
 import org.springframework.web.bind.annotation.ExceptionHandler;
 import org.springframework.web.bind.annotation.RestControllerAdvice;
 import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

 import java.util.HashMap;
 import java.util.Map;

 /**
  * <p>Project: sboot_2023-cn.shun.advice-MyResponseAdvice
  * <p>Powered by yishun On 2023-04-14 19:14:55
  *
  * @author yishun [2465734101@qq.com]
  * @version 1.0
  * @since 17
  */
 @RestControllerAdvice("cn.shun.controller")
 public class MyResponseAdvice implements ResponseBodyAdvice<Object> {


     @Override
     public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
         return true;
     }

     @ExceptionHandler
     public Object processException(Exception ex) {
         if (ex instanceof BizException) {
             BizException exception = (BizException) ex;
             return ResponseDto.error(exception.getCode(), ex.getMessage());

         }
         ex.printStackTrace();
         return ResponseDto.error(1, ex.getMessage());
     }

     @Override
     public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
         ResponseDto responseDto = null;
         PageInfoDto pageInfoDto = PageInfoThreadLocal.get();
         if (pageInfoDto != null) {
             long total = pageInfoDto.getTotal();
             Map<String, Object> map = new HashMap<>();
             map.put("total", total);
             map.put("items", body);
             responseDto = ResponseDto.success(map);
             PageInfoThreadLocal.clean();
         } else {

             responseDto = ResponseDto.success(body);
         }
         if (selectedConverterType == StringHttpMessageConverter.class) {
             return JSONUtil.toJsonStr(responseDto);
         }
         return responseDto;
     }
 }
